<template>
    <w-tab-list  @clear-search="clearSearch(true)"
                 @clear-selection="clearSelection"
                 @refresh-data="refreshData(true)"
                 @search-active="searchActive"
                 @delete-batch="remove"
                 @open-add-from="insert"
                 :total="paging.total"
                 :page-size="paging.pageSize"
                 :frame="false"
                 :page-bar="false"
    >
        <template #searchItem>
            <ul style="float:left;">
                <li>
                    菜单名称：<el-input type="text" placeholder="请输入菜单名称" class="sh" v-model="search.menuName"/>
                </li>
                <li>
                    状态：<el-select v-model="search.enabled" placeholder="菜单状态" clearable>
                    <el-option label="正常" :value="1"/>
                    <el-option label="停用" :value="0"/>
                </el-select>
                </li>
<!--                <li>-->
<!--                    创建时间：<el-date-picker v-model="search.date" type="daterange" size="default" start-placeholder="start" end-placeholder="end" clearable class="picker"/>-->
<!--                </li>-->
            </ul>
        </template>
        <template #batchOperationItem>
            <el-button @click="importData" :icon="Upload" class="import">导入</el-button>
            <el-button @click="exportData" :icon="Download" class="export">导出</el-button>
        </template>
        <template #dataList>
            <el-table
                      :data="menuData"
                      row-key="id"
                      size="small"
                      ref="menuTable"
                      class="menuTable"
                      v-loading="loading"
                      element-loading-text="正在加载菜单数据"
                      @select="customSelectRow"
                      @select-all="customSelectAll"
                      @row-dblclick="rowDblclick"
                      stripe
            >
                <el-table-column type="selection" width="30"/>
                <el-table-column prop="id" label="菜单编号" width="100px"/>
                <el-table-column prop="menuName" label="菜单名称" width="160"/>
                <el-table-column label="菜单图标" width="80" align="center">
                    <template #default="s">
                        <template v-if="s.row.iconUrl">
                            <img :src="`/${s.row.iconUrl}`" class="icon"/>
                        </template>
                    </template>
                </el-table-column>
                <el-table-column label="显示顺序" prop="sort" width="80" align="center"/>
<!--                <el-table-column prop="url" label="域名"/>-->
                <el-table-column prop="path" label="路由地址" show-overflow-tooltip/>
                <el-table-column prop="component" label="路由组件" show-overflow-tooltip/>
                <el-table-column label="状态" width="80">
                    <template #default="s">
                        <!--                        <el-switch v-model="s.row.enabled"-->
                        <!--                                   :active-value="1"-->
                        <!--                                   :inactive-value="0"-->
                        <!--                                   :before-change="switchEnabled"-->
                        <!--                                   @change="enableChange($event,s.row)"-->
                        <!--                                   size="small"-->
                        <!--                        />-->
                        <template v-if="s.row.enabled === 1">
                            <el-tag type="success">正常</el-tag>
                        </template>
                        <template v-else>
                            <el-tag type="warning">禁用</el-tag>
                        </template>
                    </template>
                </el-table-column>
                <el-table-column label="菜单类型" width="80">
                    <template #default="s">
                        <template v-if="s.row.type===0">
                            目录
                        </template>
                        <template v-if="s.row.type===1">
                            菜单
                        </template>
                        <template v-if="s.row.type===2">
                            按钮
                        </template>
                    </template>
                </el-table-column>
                <el-table-column label="认证" width="60px">
                    <template #default="s">
                        <template v-if="s.row.requireAuth === 1">
                            <lock style="width: 18px;height: 18px"/>
                        </template>
                    </template>
                </el-table-column>
<!--                <el-table-column prop="keepAlive" label="是否激活"/>-->
                <el-table-column prop="createTime" label="创建时间"/>
                <el-table-column label="操作" width="200">
                    <template #default="s">
                        <el-button type="text" size="small" @click="edit(s.row)" :icon="Edit">编辑</el-button>
                        <el-button type="text" size="small" @click="insert(s.row)" :icon="Plus">新增</el-button>
                        <el-button type="text" size="small" @click="remove(s.row)" :icon="Delete">删除</el-button>
                        <el-button type="text" size="small" @click="look(s.row)" :icon="View"></el-button>
                    </template>
                </el-table-column>
            </el-table>
        </template>
    </w-tab-list>
    <menu-form width="42%" @refresh-data="refreshData" ref="menuForm"/>
    <data-import action="http://localhost:8001/sys/menu/import" @upload-success="uploadSuccess" ref="importComps"/>
</template>

<script>
    import {Search,Refresh,RefreshRight,CollectionTag,Delete,Plus,Edit,DArrowRight,Picture,Failed,View,Upload,Download,Lock} from '@element-plus/icons-vue'
    import {ElLoading, ElMessage} from 'element-plus'
    import WTabList from "../../com/WTabList.vue";
    import {deleteMenu, exportMenu, getMenuOptions, getMenus, updateMenu} from "../../../network/sys/menu";
    import MenuForm from "./form/MenuForm.vue";
    import DataImport from "../../com/DataImport.vue";
    import {deleteRole} from "../../../network/sys/role";

    export default {
        name: "MenuMain",
        components:{
            DataImport,
            MenuForm,
            WTabList,
        },
        setup(props,{emit}){
            return{
                Search,
                Refresh,
                RefreshRight,
                CollectionTag,
                Delete,
                Plus,
                Edit,
                DArrowRight,
                Picture,
                Failed,
                View,
                Download,
                Upload,
                Lock
            }
        },
        data(){
            return{
                menuData: [],
                checkedAll: false,
                search:{
                    menuName: null,
                    enabled: null
                },
                paging:{
                    total: 100,//记录总数
                    pageSize: 9,//每页记录数
                    pageNum: 1,//当前页码
                    pagerCount: 8,//最大页码按钮数，限定在(5 ≤ x ≤ 21 的奇数)
                },
                loading: false
            }
        },
        methods:{
            customSelectRow(selection,row){
                //级联选择
                if(Array.isArray(row.children) && row.children.length!==0){
                    row.children.forEach(r=>{
                        this.$refs.menuTable.toggleRowSelection(r,null);
                        this.customSelectRow(null,r);
                    })
                }
            },
            customSelectAll(selection){
                this.checkedAll = !this.checkedAll;
                this.toggleCheckedAll(this.menuData,this.checkedAll);
                // console.log('全选选择的',selection);
            },
            toggleCheckedAll(tableData,flag){
                tableData.forEach(row=>{
                    this.$refs.menuTable.toggleRowSelection(row,flag);
                    if(Array.isArray(row.children) && row.children.length!==0){
                        this.toggleCheckedAll(row.children,flag);
                    }
                })
            },
            rowDblclick(row, column, event){
                // console.log('selection',)
                // console.log('row',row);
                // console.log('event',event);
                // let array = [1, 2, 3, 4];
                // let set = new Set(array);
                // let demo = new Set([1,2,3,4]);
                // Array.from(demo)
                // console.log('set',set)
            },
            uploadSuccess(){
                this.refreshData();
                this.$refs.importComps.visible=false;
            },
            importData(){
                this.$refs.importComps.visible=true;
            },
            exportData(){
                exportMenu().then(vo=>{
                    this.$utils.exportExcel({
                        data:vo,
                        fileName: '菜单表'
                    });
                })
            },
            /*1、搜索框管理*/
            //搜索执行函数
            searchActive(){
                this.$utils.searchActive({
                    data: this.search,
                    initData: this.$options.data.call(this).search,
                    executeFn:()=>{
                        this.loadMenusData();
                    }
                })
            },
            //清空搜索框
            clearSearch(hint){
                this.$utils.resetSearchParams({
                    initData: this.$options.data.call(this).search,
                    data: this.search,
                    hint: hint,
                    callback: ()=>{
                        this.loadMenusData();
                    }
                });
            },
            //删除菜单
            remove(row){
                if(row){
                    this.$operate.remove({
                        title: '删除菜单',
                        data: `菜单 ' ${row.menuName} '`,
                        hint: '这将会删除当前菜单。',
                        executeFn: ()=>{
                            this.deleteExecute([row.id]);
                        }
                    })
                }else{
                    this.$operate.removeBatch({//1.确认操作，提取selection参数。
                        title: '批量删除菜单',
                        hint: '这将会删除当前选中的菜单。',
                        selection: this.$refs.menuTable.getSelectionRows(),
                        key: 'id',
                        executeFn: (ids)=>{//2.执行删除操作
                            this.deleteExecute(ids);
                        }
                    })
                }
            },
            deleteExecute(ids){
                deleteMenu(ids).then(vo=>{
                    this.$response.handle({
                        data: vo,
                        success: '删除成功',
                        error: '删除失败',
                        successFn: ()=>{
                            this.refreshData();
                            this.loadMenuOptions();
                        }
                    })
                })
            },
            //修改状态
            switchEnabled(){
                return this.$operate.switchStatus({
                    title: '修改菜单状态',
                    hint: '你确认要更改该菜单状态吗'
                });
            },
            //修改状态执行
            enableChange($event,row){
                // console.log('val',$event);
                // console.log('id',row.id)
                updateMenu({id: row.id, enabled: $event}).then(data=>{
                   this.$response.handle({
                       data:data,
                       success: '修改成功',
                       error: '修改失败'
                   })
                })
            },
            // /*3.分页管理*/
            /*4.对话框管理*/
            //打开新增对话框
            insert(row){
                // console.log('row',row)
                let frm = this.$refs.menuForm
                frm.visible = true;
                frm.type = 0;
                frm.title = '添加菜单';
                if(row){
                    this.$nextTick(function (){
                        frm.focusPath();
                        let obj = {
                            parentId: row.id,
                            path: row.path,
                            sort: row.children ? row.children.length + 1 : 1,
                            type: row.type===0 ?  1 : (row.type===1 ? 2 : 0),
                            requireAuth: 1,
                            keepAlive: 1,
                            enabled: 1
                        }
                        frm.setObj(obj)
                    })
                }
            },
            //编辑记录
            edit(row){
                // console.log('row',row)
                let frm = this.$refs.menuForm;
                frm.visible = true;
                frm.type = 1;
                frm.title = '修改菜单';
                this.$nextTick(function (){
                    frm.setObj(row);
                })
                // frm.menu = this.$utils.clone(row);
                // frm.originMenu = this.$utils.clone(row);

            },
            /*5.表格管理*/
            //刷新表格数据
            refreshData(hint){
                this.loadMenusData(hint);
                this.loadMenuOptions();
            },
            clearSelection(){
                this.$refs.menuTable.clearSelection();
            },
            /*6.数据加载项*/
            loadMenusData(hint){
                this.loading = true;
                getMenus(this.search).then(data=> {
                    this.loading = false;
                    this.$response.handle({//请求结果处理
                        // log: '菜单数据',
                        data: data,
                        successFn: () => {
                            this.menuData = this.$utils.convertTree({
                                data: data.data,
                                id: 'id',
                                parentId: 'parentId',
                                children: 'children'
                            })
                            if (hint) {
                                ElMessage.success('刷新成功');
                            }
                        }
                    })
                })
            },
            loadMenuOptions(){
                getMenuOptions().then(vo=>{
                    this.$response.handle({
                        data: vo,
                        successFn: ()=>{
                            this.$store.commit('setMenuOptions',vo.data);
                        },
                        // log: '菜单选项数据'
                    })
                })
            },
            look(row){
                window.open(row.url + row.path);
            },
            init(){
                this.loadMenusData();
                if(this.$store.state.menuOptions.length===0){
                    this.loadMenuOptions();
                }
            }
        },
        created() {
            this.init();
        }
    }
</script>

<style scoped>
    .tab-list{
        height: 99%;
    }
    .sh{
        width: 180px;
    }
    .el-select-dropdown__item{
        width: 100%;
        color: darkgray;
    }
    .el-select{
        width: 120px;
    }
    .icon{
        width: 18px;
    }
    .el-scrollbar__view{
        width: 200px;
    }
    .import{
        color: #ffba00;
        background: #fff8e6;
        border-color: #ffe399;
    }
    .import:hover{
        opacity:0.6;
    }
    .export{
        color: #e019195e;
        background: #f3f3bfc2;
        border-color: #ffe399;
    }
    .export:hover{
        opacity: 0.6;
    }
</style>
